package com.gy.dalian.controller;

import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.operator.Equal;
import com.ejlchina.searcher.util.MapUtils;
import com.mysql.cj.util.StringUtils;
import com.gy.dalian.common.AjaxResult;
import com.gy.dalian.model.DldpUser;
import com.gy.dalian.service.DldpUserService;
import com.gy.dalian.util.Md5Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @author:23562
 * @date:2023/3/18 Cannot destructure property 'token' of 'e.data' as it is undefined.
 */
@Controller("/dw-service-xxl-screen")
@CrossOrigin(origins = "*")
@RequiredArgsConstructor
public class LoginController {

    private final BeanSearcher beanSearcher;
    private DldpUserService dldpUserService;
    private final String CITY = "2";

    @RequestMapping("/bgLogin")
    public String bgLogin() {
        return "/dldp_bg/index";
    }

    @RequestMapping("login")
    @ResponseBody
    public ResponseEntity<AjaxResult> login(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
        if (StringUtils.isNullOrEmpty(userName) || StringUtils.isNullOrEmpty(passWord)) {
            return ResponseEntity.ok(AjaxResult.error("用户名和密码为空，请输入后重新操作"));
        }

        String pass = Md5Utils.inputPassToFormPass(passWord);
        Map<String, Object> params = MapUtils.builder()
                .field(DldpUser::getUserName, userName).op(Equal.class)
                .field(DldpUser::getCity, CITY).op(Equal.class)
                .build();
        DldpUser user = beanSearcher.searchFirst(DldpUser.class, params);
        if (user == null) {
            return ResponseEntity.ok(AjaxResult.error("该用户不存在，请重新输入"));
        }
        if (Objects.equals(user.getPassWord(), pass)) {
//          String token = JwtUtils.getJwtToken(user.getId(), user.getUserName());
            String token = UUID.randomUUID().toString();
            map.put("token", token);
            map.put("msg", "操作成功");
            return ResponseEntity.ok(AjaxResult.successData(200, map));
        } else {
            return ResponseEntity.ok(AjaxResult.error("密码错误，请输入后重新操作"));
        }
    }


}
